import { closeCaseApi, getFinCloseCasePageApi } from "@/api/approval/financeClosing";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { Ref } from "vue";
export default function OperationHook(state: {
  searchForm: FinanceClosing.SearchForm;
  tableData: Ref<Array<FinanceClosing.ListRows>>;
  drawerOpts: Base.DrawerOpts;
  loading: Ref<boolean>;
  activeKey: Ref<number>;
}) {
  const { searchForm, tableData, drawerOpts, loading, activeKey } = state;

  const getData = () => {
    const params = {
      ...getParams(),
      isCloseCase: activeKey.value
    };

    loading.value = true;
    return getFinCloseCasePageApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const getParams = () => {
    const { waybillNumList, problemPieceTypeList, createByList, time, pageNum, pageSize, total, customerIdList } = searchForm;
    const params: FinanceClosing.SearchParams = {
      waybillNumList: [],
      customerIdList,
      problemPieceTypeList,
      createByList,
      createStartTime: time.length ? dayjs(time[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      createEndTime: time.length ? dayjs(time[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      total,
      pageNum,
      pageSize
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    return params;
  };

  const searchHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };

  //查看
  const checkProblemHandle = (row: FinanceClosing.ListRows) => {
    drawerOpts.title = "查看";
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "CheckProblem";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  //结案
  const closeCaseHandle = (row: FinanceClosing.ListRows) => {
    return closeCaseApi([row.id]).then(({ code }: any) => {
      if (code === 200) {
        message.success("操作成功");
        getData();
      }
    });
  };

  return {
    searchHandle,
    getData,
    checkProblemHandle,
    closeCaseHandle
  };
}
